package com.myCompany.edu.realtime.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myCompany.edu.realtime.app.BaseAppV1;
import com.myCompany.edu.realtime.bean.CourseCaSubCourOrderBean;
import com.myCompany.edu.realtime.common.Constant;
import com.myCompany.edu.realtime.util.DateUtils;
import com.myCompany.edu.realtime.util.DimUtil;
import com.myCompany.edu.realtime.util.DruidDSUtil;
import com.myCompany.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.sql.Connection;
import java.time.Duration;

/*
    课程域类别-学科-课程粒度下单各窗口汇总表


 */
public class Dws10_DwsCourseCateSubCourseOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws10_DwsCourseCateSubCourseOrderWindow().init(3010,1,"Dws10_DwsCourseCateSubCourseOrderWindow", Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
//        stream.print();
        
        // 1. 封装成bean
        SingleOutputStreamOperator<CourseCaSubCourOrderBean> beanStream = parseToBean(stream);
//        beanStream.print();

        // 2. 补充其他id及维度信息（需要其他id来keyby开窗，所以先补充信息）
        beanStream = addRefData(beanStream);

        // 3. 开窗聚合
        SingleOutputStreamOperator<CourseCaSubCourOrderBean> resultStream = winAndAgg(beanStream);
//        resultStream.print();

        // 4. 写出到clickhouse
        writeToClickhouse(resultStream);

    }

    private void writeToClickhouse(SingleOutputStreamOperator<CourseCaSubCourOrderBean> resultStream) {
        resultStream.addSink(
                FlinkSinkUtil.getClickHouseSink("dws_course_cate_sub_course_order_window",CourseCaSubCourOrderBean.class));
    }

    private SingleOutputStreamOperator<CourseCaSubCourOrderBean> winAndAgg(SingleOutputStreamOperator<CourseCaSubCourOrderBean> beanStream) {
        return beanStream.assignTimestampsAndWatermarks(
                WatermarkStrategy.<CourseCaSubCourOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean,ts)->bean.getTs())
        )
                .keyBy(bean->bean.getCategoryId() + "_" + bean.getSubjectId() + "_" + bean.getCourseId())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<CourseCaSubCourOrderBean>() {
                            @Override
                            public CourseCaSubCourOrderBean reduce(CourseCaSubCourOrderBean value1, CourseCaSubCourOrderBean value2) throws Exception {
                                value1.setOrderCount(value1.getOrderCount() + value2.getOrderCount());
                                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));

                                return value1;
                            }
                        },
                        new ProcessWindowFunction<CourseCaSubCourOrderBean, CourseCaSubCourOrderBean, String, TimeWindow>() {
                            @Override
                            public void process(String key, Context ctx, Iterable<CourseCaSubCourOrderBean> iterable, Collector<CourseCaSubCourOrderBean> out) throws Exception {

                                CourseCaSubCourOrderBean bean = iterable.iterator().next();
                                bean.setStt(DateUtils.toDateTime(ctx.window().getStart()));
                                bean.setEdt(DateUtils.toDateTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        });
    }

    private SingleOutputStreamOperator<CourseCaSubCourOrderBean> addRefData(SingleOutputStreamOperator<CourseCaSubCourOrderBean> beanStream) {
        return beanStream.map(new RichMapFunction<CourseCaSubCourOrderBean, CourseCaSubCourOrderBean>() {


            private Connection conn;

            @Override
            public void open(Configuration parameters) throws Exception {
                DruidDataSource dataSource = DruidDSUtil.getDataSource();
                conn = dataSource.getConnection();
            }

            @Override
            public void close() throws Exception {
                if (conn != null){
                    conn.close();
                }
            }

            @Override
            public CourseCaSubCourOrderBean map(CourseCaSubCourOrderBean bean) throws Exception {
                // dim_course_info
                JSONObject dimCourseInfo = DimUtil.readDimFromPhoenix(conn, "dim_course_info", bean.getCourseId());
                String subjectId = dimCourseInfo.getString("SUBJECT_ID");
//                System.out.println("-----subjectId----:" + subjectId);

                // dim_base_subject_info
                JSONObject dimBaseSubjectInfo = DimUtil.readDimFromPhoenix(conn, "dim_base_subject_info", subjectId);
                String subjectName = dimBaseSubjectInfo.getString("SUBJECT_NAME");
                String categoryId = dimBaseSubjectInfo.getString("CATEGORY_ID");

//                System.out.println("-----subjectName----:" + subjectName);
//                System.out.println("-----categoryId----:" + categoryId);


                //dim_base_category_info
                JSONObject dimBaseCategoryInfo = DimUtil.readDimFromPhoenix(conn, "dim_base_category_info", categoryId);
                String categoryName = dimBaseCategoryInfo.getString("CATEGORY_NAME");

//                System.out.println("-----categoryName----:" + categoryName);


                bean.setCategoryId(categoryId);
                bean.setCategoryName(categoryName);
                bean.setSubjectId(subjectId);
                bean.setSubjectName(subjectName);

                return bean;
            }
        });

    }


    private SingleOutputStreamOperator<CourseCaSubCourOrderBean> parseToBean(DataStreamSource<String> stream) {
        /*
            源order_detail数据粒度是一个订单的一个课程，一个订单可能下单很多课程,所以订单数需要去重
            将order_id放在一起,取第一条
            使用状态去重：如果状态中已有这个order_id,orderCount就不变，若没有，就+1
         */
        return stream
                .map(str->JSON.parseObject(str))
                .keyBy(jsonstr->jsonstr.getString("order_id"))
                .process(new KeyedProcessFunction<String, JSONObject, CourseCaSubCourOrderBean>() {

                    private ValueState<String> orderIdState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 状态直接存储orderId，判断时若存在就不增加count数
                        orderIdState = getRuntimeContext().getState(new ValueStateDescriptor<String>("orderIdState", String.class));
                    }


                    @Override
                    public void processElement(JSONObject data, Context ctx, Collector<CourseCaSubCourOrderBean> out) throws Exception {

                        String courseId = data.getString("course_id");
                        String courseName = data.getString("course_name");
                        String orderId = data.getString("order_id");
//                        System.out.println("---------当前order_id:"  + orderId);


                        // 下单次数
                        // 若状态中存在，就不变，不存在，就count+1，并更新状态
                        Long orderCount = 0l;

                        if (orderIdState.value() == null){
//                            System.out.println("状态中order_id:===========" + orderIdState.value());
                            orderCount = 1l;
                            orderIdState.update(orderId);
                        }

                        BigDecimal orderAmount = data.getBigDecimal("split_final_amount");
                        Long ts = data.getLong("ts")*1000;

                        out.collect( new CourseCaSubCourOrderBean(
                                "","","","","","",
                                courseId,courseName,orderCount,orderAmount,ts
                        ));
                    }
                });

    }
}
